<template>
  <div class="article-create-container">
    <el-card class="article-card">
      <template #header>
        <div class="card-header">
          <h2>发布文章</h2>
          <el-button 
            type="primary" 
            @click="openDrafts"
            v-if="isLoggedIn"
          >
            <el-icon><Document /></el-icon>我的草稿
            <el-badge v-if="draftCount > 0" :value="draftCount" class="draft-badge" />
          </el-button>
        </div>
      </template>
      
      <el-form
        :model="articleForm"
        :rules="articleRules"
        label-position="top"
        @submit.prevent
      >
        <!-- 标题 -->
        <el-form-item label="文章标题" prop="title">
          <el-input
            v-model="articleForm.title"
            placeholder="请输入标题（5-50个字符）"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>
        
        <!-- 板块选择 -->
        <el-form-item label="所属板块" prop="boardId">
          <el-select
            v-model="articleForm.boardId"
            placeholder="请选择板块"
            style="width: 100%"
          >
            <el-option
              v-for="board in boards"
              :key="board.id"
              :label="board.name"
              :value="board.id"
            />
          </el-select>
        </el-form-item>
        
        <!-- 标签 -->
        <el-form-item label="文章标签" prop="tags">
          <el-tag
            v-for="tag in dynamicTags"
            :key="tag"
            closable
            class="tag-item"
            @close="handleTagClose(tag)"
          >
            {{ tag }}
          </el-tag>
          
          <el-input
            v-if="tagInputVisible"
            ref="tagInputRef"
            v-model="tagInputValue"
            class="tag-input"
            size="small"
            @keyup.enter="handleTagInputConfirm"
            @blur="handleTagInputConfirm"
          />
          
          <el-button
            v-else
            class="tag-add-button"
            size="small"
            @click="showTagInput"
          >
            + 添加标签
          </el-button>
          
          <div class="tag-tip">最多添加5个标签，每个标签不超过10个字符</div>
        </el-form-item>
        
        <!-- 摘要 -->
        <el-form-item label="文章摘要" prop="summary">
          <el-input
            v-model="articleForm.summary"
            type="textarea"
            placeholder="请输入文章摘要（选填，最多200个字符）"
            :rows="3"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
        
        <!-- Markdown编辑器 -->
        <el-form-item label="文章内容" prop="content">
          <MdEditor
            v-model="articleForm.content"
            style="height: 500px"
            :preview="true"
            :toolbarsExclude="['github']"
            placeholder="请输入文章内容..."
            @onUploadImg="handleImgAdd"
            codeTheme="atom-one-dark"
            previewTheme="vuepress"
            :noMermaid="false"
            :noKatex="false"
            :config="{
              uploadImgShowBase64: false,
              uploadImgMaxSize: 10 * 1024 * 1024,
              markdownUrl: ''
            }"
          />
        </el-form-item>
        
        <!-- 提交按钮 -->
        <el-form-item>
          <div class="form-actions">
            <el-button @click="handleCancel">取消</el-button>
            <el-button type="primary" @click="handleSubmit" :loading="submitting">发布文章</el-button>
            <el-button type="info" @click="handleDraft">保存草稿</el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 草稿列表抽屉 -->
    <el-drawer
      title="我的草稿"
      v-model="showDrafts"
      direction="rtl"
      size="50%"
    >
      <div class="drafts-container">
        <el-empty v-if="drafts.length === 0" description="暂无草稿"></el-empty>
        <el-table v-else :data="drafts" style="width: 100%">
          <el-table-column prop="title" label="标题" min-width="180"></el-table-column>
          <el-table-column prop="updateTime" label="更新时间" width="160">
            <template #default="scope">
              {{ formatDate(scope.row.updateTime) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180">
            <template #default="scope">
              <el-button type="primary" size="small" @click="editDraft(scope.row)">编辑</el-button>
              <el-button type="success" size="small" @click="publishDraft(scope.row.id)">发布</el-button>
              <el-button type="danger" size="small" @click="deleteDraft(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-drawer>
    
    <!-- 草稿快捷按钮 -->
    <el-button
      class="drafts-button"
      type="primary"
      circle
      @click="openDrafts"
      v-if="isLoggedIn"
    >
      <el-icon><Document /></el-icon>
    </el-button>
    <span class="drafts-count" v-if="draftCount > 0">{{ draftCount }}</span>
  </div>
</template>

<script>
import { ref, reactive, computed, nextTick, onMounted } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import api from '@/api'
import { Plus, Document } from '@element-plus/icons-vue'
import MdEditor from 'md-editor-v3'
import 'md-editor-v3/lib/style.css'
import axios from 'axios'
import config from '@/config'

export default {
  name: 'ArticleCreate',
  components: {
    Plus,
    Document,
    MdEditor
  },
  setup() {
    const store = useStore()
    const router = useRouter()
    
    const tagInputRef = ref(null)
    const submitting = ref(false)
    
    // 表单数据
    const articleForm = reactive({
      title: '',
      boardId: '',
      tags: '',
      summary: '',
      content: '',
      html: '',
      isDraft: false
    })
    
    // 表单验证规则
    const articleRules = {
      title: [
        { required: true, message: '请输入文章标题', trigger: 'blur' },
        { min: 5, max: 50, message: '标题长度应在5到50个字符之间', trigger: 'blur' }
      ],
      boardId: [
        { required: true, message: '请选择板块', trigger: 'change' }
      ],
      content: [
        { required: true, message: '请输入文章内容', trigger: 'blur' },
        { min: 10, message: '内容太短，至少10个字符', trigger: 'blur' }
      ]
    }
    
    // 板块列表
    const boards = computed(() => store.state.boards || [])
    
    // 标签相关
    const dynamicTags = ref([])
    const tagInputVisible = ref(false)
    const tagInputValue = ref('')
    
    // 上传相关
    const uploadHeaders = computed(() => {
      const token = localStorage.getItem('token')
      return { Authorization: token }
    })
    
    // 草稿相关
    const showDrafts = ref(false)
    const drafts = ref([])
    const draftCount = computed(() => store.getters['article/getDraftCount'])
    const isLoggedIn = computed(() => store.getters['user/isLoggedIn'])
    
    // 方法
    const showTagInput = () => {
      if (dynamicTags.value.length >= 5) {
        ElMessage.warning('最多添加5个标签')
        return
      }
      
      tagInputVisible.value = true
      nextTick(() => {
        tagInputRef.value.focus()
      })
    }
    
    const handleTagInputConfirm = () => {
      const inputValue = tagInputValue.value.trim()
      
      if (inputValue && !dynamicTags.value.includes(inputValue)) {
        if (inputValue.length > 10) {
          ElMessage.warning('标签长度不能超过10个字符')
        } else {
          dynamicTags.value.push(inputValue)
          // 更新表单中的tags字段
          articleForm.tags = dynamicTags.value.join(',')
        }
      }
      
      tagInputVisible.value = false
      tagInputValue.value = ''
    }
    
    const handleTagClose = (tag) => {
      dynamicTags.value = dynamicTags.value.filter(t => t !== tag)
      // 更新表单中的tags字段
      articleForm.tags = dynamicTags.value.join(',')
    }
    
    // 处理编辑器图片上传
    const handleImgAdd = async (files, insertCallback) => {
      try {
        console.log('开始上传图片...');
        
        if (!files || files.length === 0) return;
        
        const file = files[0];
        const formData = new FormData();
        formData.append('file', file);
        
        // 获取token，用于认证
        const token = localStorage.getItem('token');
        if (!token) {
          ElMessage.error('请先登录后再上传图片');
          return;
        }
        
        // 直接使用axios实例进行上传
        const response = await axios.post(
          `${config.backendUrl}/upload/image`, 
          formData, 
          {
            params: { token },
            headers: { 'Content-Type': 'multipart/form-data' }
          }
        );
        
        console.log('上传结果:', response);
        
        if (response.data && response.data.code === 0) {
          // 从message中获取图片URL
          const imageUrl = response.data.message;
          
          // 增加空值检查
          if (!imageUrl) {
            ElMessage.error('图片上传成功但未返回有效的URL');
            return;
          }
          
          console.log('后端返回的图片URL:', imageUrl);
          
          // 关键修改: md-editor-v3要求回调函数接收URL数组，而不是Markdown文本
          // 这是最符合其API规范的做法
          if (typeof insertCallback === 'function') {
            console.log('使用URL数组调用insertCallback:', [imageUrl]);
            
            // 确保URL是绝对路径，如果不是绝对路径，浏览器可能无法解析
            const urlsToInsert = [imageUrl];
            
            // 直接调用回调函数，传入URL数组
            insertCallback(urlsToInsert);
            
            ElMessage.success('图片上传成功');
          } else {
            console.error('insertCallback不是函数:', typeof insertCallback);
            ElMessage.warning('图片上传成功，但无法插入到编辑器');
          }
        } else {
          ElMessage.error('图片上传失败: ' + (response.data?.message || '未知错误'));
        }
      } catch (error) {
        console.error('上传图片出错:', error);
        ElMessage.error('图片上传失败：' + (error.message || '未知错误'));
      }
    };
    
    // 处理提交
    const handleSubmit = () => {
      // 不依赖表单验证，手动验证必填字段
      if (!articleForm.title.trim()) {
        ElMessage.warning('请输入文章标题')
        return
      }
      
      if (articleForm.title.trim().length < 5 || articleForm.title.trim().length > 50) {
        ElMessage.warning('标题长度应在5到50个字符之间')
        return
      }
      
      if (!articleForm.boardId) {
        ElMessage.warning('请选择板块')
        return
      }
      
      if (!articleForm.content.trim()) {
        ElMessage.warning('文章内容不能为空')
        return
      }
      
      if (articleForm.content.trim().length < 10) {
        ElMessage.warning('内容太短，至少10个字符')
        return
      }
      
      submitting.value = true
      articleForm.isDraft = false
      
      // 清除所有可能存在的消息
      ElMessage.closeAll()
      
      api.article.create(articleForm)
        .then(response => {
          if (response && response.code === 0) {
            ElMessage.success('文章发布成功')
            
            // 检查response.data是否存在
            if (response.data && response.data.id) {
              // 如果有文章ID，跳转到文章详情页
              router.push(`/article/${response.data.id}`)
            } else {
              // 如果没有文章ID，跳转到文章列表页
              router.push('/articles')
            }
          } else {
            // 后端返回了响应但有错误码
            console.error('发布文章失败:', response)
            ElMessage.error(response.message || '发布失败，请稍后重试')
          }
        })
        .catch(error => {
          console.error('发布文章失败:', error)
          ElMessage.error(error.message || '发布失败，请稍后重试')
        })
        .finally(() => {
          submitting.value = false
        })
    }
    
    // 保存草稿
    const handleDraft = () => {
      if (!articleForm.title.trim()) {
        ElMessage.warning('请先填写文章标题')
        return
      }
      
      submitting.value = true
      articleForm.isDraft = true
      
      // 清除所有可能存在的消息
      ElMessage.closeAll()
      
      api.article.create(articleForm)
        .then(response => {
          if (response && response.code === 0) {
            ElMessage.success('草稿保存成功')
          } else {
            // 后端返回了响应但有错误码
            console.error('保存草稿失败:', response)
            ElMessage.error(response.message || '保存失败，请稍后重试')
          }
        })
        .catch(error => {
          console.error('保存草稿失败:', error)
          ElMessage.error(error.message || '保存失败，请稍后重试')
        })
        .finally(() => {
          submitting.value = false
        })
    }
    
    // 取消发布
    const handleCancel = () => {
      if (articleForm.title || articleForm.content) {
        ElMessageBox.confirm('确定要放弃编辑吗？未保存的内容将丢失', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          router.go(-1)
        }).catch(() => {})
      } else {
        router.go(-1)
      }
    }
    
    // 加载草稿列表
    const loadDrafts = async () => {
      try {
        await store.dispatch('article/getUserDrafts')
        drafts.value = store.getters['article/getDrafts']
      } catch (error) {
        console.error('加载草稿失败:', error)
        ElMessage.error('加载草稿失败，请重试')
      }
    }
    
    // 加载草稿数量
    const loadDraftCount = async () => {
      try {
        await store.dispatch('article/countUserDrafts')
      } catch (error) {
        console.error('加载草稿数量失败:', error)
      }
    }
    
    // 打开草稿列表
    const openDrafts = async () => {
      await loadDrafts()
      showDrafts.value = true
    }
    
    // 编辑草稿
    const editDraft = (draft) => {
      articleForm.title = draft.title || ''
      articleForm.boardId = draft.boardId || ''
      articleForm.content = draft.content || ''
      articleForm.tags = draft.tags || ''
      articleForm.summary = draft.summary || ''
      articleForm.draftId = draft.id
      
      // 处理标签
      if (draft.tags) {
        dynamicTags.value = typeof draft.tags === 'string' 
          ? draft.tags.split(',').filter(tag => tag.trim())
          : draft.tags
      }
      
      showDrafts.value = false
      ElMessage.success('草稿已加载，可继续编辑')
    }
    
    // 发布草稿
    const publishDraft = async (draftId) => {
      try {
        const result = await ElMessageBox.confirm(
          '确定要发布这篇草稿吗？发布后草稿将被删除。',
          '发布确认',
          {
            confirmButtonText: '确定发布',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        if (result === 'confirm') {
          const articleId = await store.dispatch('article/publishDraft', draftId)
          if (articleId) {
            ElMessage.success('草稿发布成功！')
            await loadDraftCount()
            await loadDrafts()
            
            // 跳转到文章详情页
            router.push({ name: 'ArticleDetail', params: { id: articleId } })
          } else {
            ElMessage.error('草稿发布失败，请重试')
          }
        }
      } catch (error) {
        console.error('发布草稿时出错:', error)
      }
    }
    
    // 删除草稿
    const deleteDraft = async (draftId) => {
      try {
        const result = await ElMessageBox.confirm(
          '确定要删除这篇草稿吗？删除后无法恢复。',
          '删除确认',
          {
            confirmButtonText: '确定删除',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        if (result === 'confirm') {
          const success = await store.dispatch('article/deleteDraft', draftId)
          if (success) {
            ElMessage.success('草稿已删除')
            await loadDraftCount()
            await loadDrafts()
          } else {
            ElMessage.error('草稿删除失败，请重试')
          }
        }
      } catch (error) {
        console.error('删除草稿时出错:', error)
      }
    }

    // 格式化日期
    const formatDate = (date) => {
      if (!date) return '';
      return new Date(date).toLocaleString();
    };

    onMounted(async () => {
      // 加载板块数据
      if (boards.value.length === 0) {
        store.dispatch('fetchBoards')
      }
      
      // 加载草稿数量
      if (isLoggedIn.value) {
        await loadDraftCount()
      }
    })
    
    return {
      articleForm,
      articleRules,
      boards,
      dynamicTags,
      tagInputVisible,
      tagInputValue,
      tagInputRef,
      uploadHeaders,
      submitting,
      showTagInput,
      handleTagInputConfirm,
      handleTagClose,
      handleImgAdd,
      handleSubmit,
      handleDraft,
      handleCancel,
      showDrafts,
      drafts,
      draftCount,
      openDrafts,
      editDraft,
      publishDraft,
      deleteDraft,
      formatDate,
      isLoggedIn
    }
  }
}
</script>

<style scoped>
.article-create-container {
  max-width: 1000px;
  margin: 0 auto;
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
  font-size: 24px;
  color: #303133;
}

.draft-badge {
  margin-left: 8px;
}

.tag-item {
  margin-right: 8px;
  margin-bottom: 8px;
}

.tag-input {
  width: 100px;
  margin-right: 8px;
  vertical-align: bottom;
}

.tag-add-button {
  margin-bottom: 8px;
}

.tag-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
}

@media screen and (max-width: 768px) {
  .article-create-container {
    padding: 10px;
  }
  
  .form-actions {
    flex-direction: column;
    gap: 10px;
  }
  
  .form-actions .el-button {
    width: 100%;
  }
}

.drafts-button {
  position: fixed;
  right: 20px;
  bottom: 20px;
  z-index: 99;
}

.drafts-count {
  position: fixed;
  right: 15px;
  bottom: 50px;
  background-color: #f56c6c;
  color: white;
  border-radius: 50%;
  padding: 2px 8px;
  font-size: 12px;
  z-index: 100;
}

.drafts-container {
  padding: 20px;
}
</style> 